package com.hdw.task.service;

import com.hdw.common.util.DateUtil;
import com.hdw.common.util.SnowflakeIdWorker;
import com.hdw.common.vo.DataExecParamVO;
import com.hdw.job.api.EtlRunService;
import com.hdw.job.api.EtlTaskOdsService;
import com.hdw.job.constant.JobConstant;
import com.hdw.job.mapper.EtlGroupBatchMapper;
import com.hdw.job.service.EtlCommonServiceImpl;
import com.hdw.task.api.JobExecService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class JobExecServiceImpl implements JobExecService {

    private static Logger logger = LoggerFactory.getLogger(JobExecServiceImpl.class);

    @Autowired
    EtlCommonServiceImpl etlCommonService;
    @Autowired
    EtlRunService etlRunService;
    @Autowired
    EtlTaskOdsService etlTaskOdsService;
    @Autowired
    EtlGroupBatchMapper etlGroupBatchMapper;

    @Override
    public boolean dayBasedataExec(String startDate,String endDate,Long xxlJobId) {
        if(xxlJobId==null) {
            xxlJobId = SnowflakeIdWorker.getId();
        }
        Boolean isSuccess = true;
        try {
            Date yesterday = DateUtil.calculate(DateUtil.toDateByFormat(endDate,DateUtil.yyyyMMdd), Calendar.DAY_OF_MONTH, -1);
            startDate = DateUtil.toDateStrByFormat(yesterday,DateUtil.yyyyMMdd);
            List<DataExecParamVO> odsParamList = etlTaskOdsService.findParamVOS(startDate,endDate);
            etlRunService.runBatchJobList(odsParamList,xxlJobId, JobConstant.JOB_EXE_TYPE_SCHEDULE);
            while(!etlRunService.isGroupEnd(xxlJobId)) {
                Thread.currentThread().sleep(500);
            }
        }catch (Exception e) {
            logger.error("按天执行任务失败",e);
            isSuccess = false;
        }
        return isSuccess;
    }
}
